<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="房间" prop="estateName">
        <el-input
          v-model="queryParams.estateName"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="承租人" prop="tenantName">
        <el-input
          v-model="queryParams.tenantName"
          placeholder="请输入名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="合同类型" prop="contractType">
        <el-select
          v-model="queryParams.contractType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dict.type.dict_contract_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="周期类型" prop="paymentType">
        <el-select
          v-model="queryParams.paymentType"
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="dict in dict.type.dict_payment_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['enterprise:contract:add']"
          >新建</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['enterprise:contract:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-row :gutter="10" class="mb8">
      <el-radio-group v-model="queryParams.contractState" @change="handleQuery">
        <el-radio-button
          :label="item.value"
          v-for="(item, index) in statistics"
          :key="index"
          >{{ item.label }}（{{ item.number }}）</el-radio-button
        >
      </el-radio-group>
    </el-row>
    <div class="info">
      <i class="el-icon-info"></i> <span>已选择</span> {{ ids.length }}
      <span>项</span> <label @click="clearSelect" class="clear">清空</label>
    </div>

    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="table"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同编号" prop="contractId" width="120" />
      <el-table-column
        label="房屋"
        prop="roleName"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ generateRoom(scope.row) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="租客信息"
        prop="roleKey"
        :show-overflow-tooltip="true"
        width="150"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.tenantName }}-{{ scope.row.tenantMobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同类型" prop="contractType" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_contract_type"
            :value="scope.row.contractType"
          />
        </template>
      </el-table-column>
      <el-table-column label="周期类型" prop="paymentType" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_payment_type"
            :value="scope.row.paymentType"
          />
        </template>
      </el-table-column>
      <el-table-column label="租金（元）" prop="monthPrice" width="100" />
      <el-table-column label="押金（元）" prop="cashPledge" width="100" />
      <el-table-column label="押付方式" prop="payTypeId" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.payTypeId | payType(payTypeList) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同周期" prop="leaseStartTime" width="100">
        <template slot-scope="scope">
          <span
            >{{ scope.row.leaseStartTime }} ~ {{ scope.row.leaseEndTime }}</span
          >
        </template>
      </el-table-column>
      <el-table-column label="时长（天）" prop="leaseDaysNumber" width="100" />
      <el-table-column label="状态" prop="contractState" width="100">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dict_contract_state"
            :value="scope.row.contractState"
          />
        </template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        align="center"
        prop="updateTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['contact:list:edit']"
            >编辑</el-button
          > -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['enterprise:contract:add']"
            >详情</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleOut(scope.row)"
            v-hasPermi="['enterprise:contract:add']"
            >退房</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-timer"
            @click="handleChangeRoom(scope.row)"
            v-hasPermi="['enterprise:contract:roomChange']"
            >换房</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleDelay(scope.row)"
            v-hasPermi="['enterprise:contract:deferred']"
            >延住</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增 -->
    <Add v-model="addDialogVisible" :title="title" @success="handleQuery" />
    <!-- 详情 -->
    <Detail
      v-model="detailDialogVisible"
      :title="title"
      :contractId="id"
      :isDetail="isDetail"
    />
    <check-out :visible="openCheckOut" @closeeldialog="dialogClose"></check-out>
    <delay :visible="openDelay" @closeeldialog="dialogClose"></delay>
    <!-- 换房 -->
    <ChangeRoom v-model="changeRoomDialogVisible" />
  </div>
</template>

  <script>
import {
  getHousingAllocation,
  listPayType,
} from "@/api/house/unmount";
import { listContract, getCountContractState } from "@/api/contract";

import Add from "./components/Add.vue";
import Detail from "./components/Add.vue";
import checkOut from "./components/check-out.vue";
import delay from "./components/delay.vue";

import ChangeRoom from "./components/Change.vue";
export default {
  name: "contract",
  dicts: ["dict_payment_type", "dict_contract_state", "dict_contract_type"],
  components: {
    Add,
    Detail,
    checkOut,
    delay,
    ChangeRoom,
  },
  data() {
    return {
      openCheckOut: false,
      openDelay: false,
      //统计数据
      statistics: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      list: [],
      // 弹出层标题
      title: "",
      //表格行id
      id: undefined,
      //是否详情页
      isDetail:false,
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      detailDialogVisible: false,
      // 当前选择
      current: "0",
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 是否显示新建合同弹窗
      addDialogVisible: false,
      // 是否显示合同详情弹窗
      detailDialogVisible: false,

      // 是否显示延住弹窗
      deferredDialogVisible: false,
      // 是否显示换房弹窗
      changeRoomDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        estateName: undefined,
        tenantName: undefined,
        paymentType: undefined,
        apartmentType: undefined,
        contractState: null,
        auditState: undefined,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      payTypeList: [],
      // 表单校验
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
        roleKey: [
          { required: true, message: "权限字符不能为空", trigger: "blur" },
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" },
        ],
      },
    };
  },
  filters: {
    payType(value, list) {
      // console.log(list);
      let result = list.find((item) => {
        return item.id == value;
      });
      return result ? result.name : value;
    },
  },
  computed: {
    generateRoom() {
      return (row) => {
        let name = "";
        if (row.estateName) name += row.estateName;
        if (row.buildingName) name += row.buildingName + "栋";
        if (row.unitName) name += row.unitName + "单元";
        if (row.roomNumber) name += row.roomNumber + "号";
        return name;
      };
    },
  },
  created() {
    this.getList();
    this.getCountContractState();
    this.getPayType();
  },
  methods: {
    //关闭回调
    dialogClose() {
      this.openCheckOut = false;
      this.openDelay = false;
    },
    //获取状态统计信息
    getCountContractState() {
      getCountContractState().then((response) => {
        this.statistics = response.data;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listContract(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.contractId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleDataScope":
          this.handleDataScope(row);
          break;
        case "handleAuthUser":
          this.handleAuthUser(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addDialogVisible = true;
      this.title = "新建合同";
    },
    handleUpdate(row) {
      console.log(row);
      let { houseId } = row;
      getHousingAllocation(houseId).then((response) => {
        this.title = "编辑";
        // this.reset();
        console.log("response", response);
        this.addDialogVisible = true;
      });
    },
    //退房
    handleOut(row) {
      this.$modal.confirm("退租后，不可撤销，确定要退租吗 ？").then(() => {
        this.openCheckOut = true;
      });
    },
    handleDelay() {
      this.$modal.confirm("确定对改合同延住吗 ？").then(() => {
        this.openDelay = true;
      });
    },
    handleDetail(row) {
      this.detailDialogVisible = true;
      this.title = "详情";
      this.id = row.contractId
      this.isDetail = true
    },
    handleDeferred(row) {
      this.deferredDialogVisible = true;
      this.title = "延住";
    },
    handleChangeRoom(row) {
      this.changeRoomDialogVisible = true;
      this.title = "换房";
    },
    /** 选择角色权限范围触发 */
    dataScopeSelectChange(value) {
      if (value !== "2") {
        this.$refs.dept.setCheckedKeys([]);
      }
    },
    /** 分配用户操作 */
    handleAuthUser: function (row) {
      const roleId = row.roleId;
      this.$router.push("/system/role-auth/user/" + roleId);
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/enterprise/contract/contract/export",
        {
          ...this.queryParams,
          contractIds:this.ids
        },
        `合同列表_${new Date().getTime()}.xlsx`
      );
    },
    //请空选择项
    clearSelect() {
      this.$refs.table.clearSelection();
    },
    //获取押付方式
    getPayType() {
      listPayType().then((response) => {
        this.payTypeList = response.data;
      });
    },
  },
};
</script>
  <style lang="scss" scoped>
.title {
  font-size: 16px;
  font-weight: bold;
  color: #666;
}
.total {
  font-size: 24px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}
.left-border {
  border-left: 1px solid #999;
}
.right-border {
  border-right: 1px solid #999;
}
.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;
  span {
    color: #565c5f;
  }
  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
